"""
重建文件
"""
import os
import sys
import traceback
import typing

import requestNovelsLib


def rebuildHandleFile(filePath: str) -> typing.Union[None, str]:
	"""
	实现一个文件的重复处理, 成功返回路径, 失败返回 None
	:param filePath: 文件路径
	:type filePath: 字符串
	:return: 成功返回路径, 失败返回 None
	:rtype: 联合类型
	"""
	fileContents = requestNovelsLib.readFile(filePath)
	if fileContents is None:
		return None
	fileContents = fileContents.replace("\r", "").replace("\ufeff", "")
	keyWords = fileContents.split("\n")
	buffHumanNameList = []
	keyWord = ""
	splList: list[str] = requestNovelsLib.getNameMaybeStr()
	keyBuffS: list[str] = []
	for keyWord in keyWords:
		for maybeSeepStr in splList:
			keyWord = keyWord.replace(maybeSeepStr, " ")
			keyBuffS = keyWord.split(" ")
		for keyWord in keyBuffS:
			buffHumanNameList.append(keyWord.strip())
		keyBuffS.clear()
	keyWords.clear()
	## 缩短字符串
	buffHumanNameList = requestNovelsLib.strListAtStrip(buffHumanNameList, 0)
	buffHumanNameList = requestNovelsLib.strListToChange(buffHumanNameList, True)
	keyWords = requestNovelsLib.strListreduce(buffHumanNameList)
	keyWords = requestNovelsLib.strRemoveSubStr(keyWords)
	keyWords.sort()
	keyWords.sort(key=len)
	## 拼接成内容
	contents = "\n".join(keyWords) + "\n"
	## 写入文件
	requestNovelsLib.writeFile(contents, filePath)
	return filePath


if __name__ == '__main__':
	argvLen = len(sys.argv)
	if argvLen > 0:
		print("开始排序")
		for argvIndex in range(1, argvLen):
			fileName = sys.argv[argvIndex]
			print(f"\n\n{fileName} 文件开始\t-=============>>")
			checkFiles = requestNovelsLib.getTargetInDirAbsFilePath(fileName)
			for checkFile in checkFiles:
				try:
					handle = rebuildHandleFile(checkFile)
					if handle is not None:
						print(f"{handle} 文件结束\t-eeeeee>>")
					else:
						print(f"{handle} 文件异常\t-!!!!!!>>")
				except Exception as es:
					traceback.print_exc()
		print("\n\n排序结束")
	else:
		print("参数错误数, 请输入正确的文件或路径")
